<template>
  <div>
    <SearchForm @search="onSearch" @reset="onReset" :search-list="searchList" :search-params="searchParams">
    </SearchForm>

    <!-- 订单状态标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="order-status-tabs">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待付款" name="pending"></el-tab-pane>
      <el-tab-pane label="待确认" name="paid"></el-tab-pane>
      <el-tab-pane label="已确认" name="shipped"></el-tab-pane>
      <el-tab-pane label="已完成" name="completed"></el-tab-pane>
      <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
      <el-tab-pane label="退款/售后" name="refund"></el-tab-pane>
    </el-tabs>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-box">
          <el-table size="large" stripe border v-loading="loading" max-height="500px" :data="tableData" row-key="id"
            element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.8)"
            @selection-change="onSelect">
            <el-table-column prop="travel_name" label="旅游产品" min-width="200">
            </el-table-column>
            <el-table-column prop="user" label="下单用户" width="100">
              <template slot-scope="scope">
                <div v-if="scope.row.user">
                  <div>{{ scope.row.user.nickname || '未知用户' }}</div>
                  <div style="color: #999; font-size: 12px;">{{ scope.row.user.phone || '无手机号' }}</div>
                </div>
                <span v-else>用户信息缺失</span>
              </template>
            </el-table-column>
            <el-table-column prop="contact_name" label="联系人" width="100">
              <template slot-scope="scope">
                <div v-if="scope.row.contact_name && scope.row.contact_phone">
                  <div>{{ scope.row.contact_name }}</div>
                  <div style="color: #999; font-size: 12px;">{{ scope.row.contact_phone }}</div>
                </div>
                <span v-else>用户信息缺失</span>
              </template>
            </el-table-column>
            <el-table-column prop="contact_name" label="经纪人" width="100">
              <template slot-scope="scope">
                <div v-if="scope.row.shareUser">
                  <div>{{ scope.row.shareUser.nickname }}</div>
                  <div style="color: #999; font-size: 12px;">{{ scope.row.shareUser.phone }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="travel_date" label="出发日期" width="120" fixed="left" />
            <el-table-column prop="adult_count" label="成人数量" width="80" />
            <el-table-column prop="child_count" label="儿童数量" width="80" />
            <el-table-column prop="room_count" label="单房差数量" width="100" />
            <el-table-column prop="payment_amount" label="支付金额" width="120">
              <template slot-scope="scope">
                <el-popover placement="top-start" width="400" trigger="hover" popper-class="payment-detail-popover">
                  <div slot="reference" class="payment-amount">
                    ¥{{ scope.row.payment_amount }}
                    <i class="el-icon-info" style="margin-left: 5px; color: #909399;"></i>
                  </div>
                  <div class="payment-detail">

                    <div v-if="getAdultItems(scope.row).length > 0">
                      <div class="detail-item">
                        <span class="label">成人单价：</span>
                        <span class="value">¥{{ getAdultItems(scope.row)[0]?.price || 0 }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">成人数量：</span>
                        <span class="value">{{ getAdultItems(scope.row).length }}人</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">成人小计：</span>
                        <span class="value">¥{{ getAdultTotal(scope.row, 'adult') }}</span>
                      </div>
                    </div>
                    <hr style="margin: 8px 0; border: none; border-top: 1px solid #EBEEF5;">

                    <!-- 从travelOrderItems获取儿童信息 -->
                    <div v-if="getChildItems(scope.row).length > 0">
                      <div class="detail-item">
                        <span class="label">儿童单价：</span>
                        <span class="value">¥{{ getChildItems(scope.row)[0]?.price || 0 }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">儿童数量：</span>
                        <span class="value">{{ getChildItems(scope.row).length }}人</span>
                      </div>
                      <div class="detail-item">
                        <span class="label">儿童小计：</span>
                        <span class="value">¥{{ getChildTotal(scope.row, 'child') }}</span>
                      </div>
                    </div>
                    <hr style="margin: 8px 0; border: none; border-top: 1px solid #EBEEF5;">

                    <div class="detail-item" v-if="scope.row.single_price_diff > 0">
                      <span class="label">单房差价格：</span>
                      <span class="value">¥{{ scope.row.single_price_diff || 0 }}</span>
                    </div>
                    <div class="detail-item" v-if="scope.row.room_count > 0">
                      <span class="label">单房差数量：</span>
                      <span class="value">{{ scope.row.room_count || 0 }}间</span>
                    </div>
                    <div class="detail-item" v-if="scope.row.single_room_diff_amount > 0">
                      <span class="label">单房差小计：</span>
                      <span class="value">¥{{ scope.row.single_room_diff_amount || 0 }}</span>
                    </div>
                    <hr v-if="scope.row.single_room_diff_amount > 0"
                      style="margin: 8px 0; border: none; border-top: 1px solid #EBEEF5;">

                    <div class="detail-item" v-if="scope.row.hotel_level_name">
                      <span class="label">酒店级别：</span>
                      <span class="value">{{ scope.row.hotel_level_name }}</span>
                    </div>
                    <div class="detail-item" v-if="scope.row.hotel_level_amount > 0">
                      <span class="label">酒店费用：</span>
                      <span class="value">¥{{ scope.row.hotel_level_amount }}</span>
                    </div>

                    <hr style="margin: 8px 0; border: none; border-top: 1px solid #EBEEF5;">
                    <!-- <div class="detail-item">
                      <span class="label">计算总价：</span>
                      <span class="value highlight">¥{{ calculateTotalPrice(scope.row) }}</span>
                    </div> -->
                    <!-- 经纪人代付 -->
                    <div class="detail-item" v-if="scope.row.prepay_amount > 0">
                      <span class="label">经纪人代付：</span>
                      <span class="value">-¥{{ scope.row.prepay_amount || 0 }}</span>
                    </div>
                    <hr v-if="scope.row.prepay_amount > 0"
                      style="margin: 8px 0; border: none; border-top: 1px solid #EBEEF5;">
                    <div class="detail-item">
                      <span class="label">实付金额：</span>
                      <span class="value highlight">¥{{ scope.row.payment_amount || 0 }}</span>
                    </div>
                    <div class="detail-item" v-if="scope.row.travel_share_price > 0">
                      <span class="label">成人佣金：</span>
                      <span class="value">-¥{{ scope.row.travel_share_price * scope.row.adult_count }}</span>
                    </div>
                    <div class="detail-item" v-if="scope.row.travel_share_price2 > 0">
                      <span class="label">儿童佣金：</span>
                      <span class="value">-¥{{ scope.row.travel_share_price2 * scope.row.child_count }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">实际收入：</span>
                      <span class="value">¥{{ scope.row.payment_amount - scope.row.travel_share_price *
                        scope.row.adult_count - scope.row.travel_share_price2 * scope.row.child_count }}</span>
                    </div>
                    <!-- <div class="detail-item" v-if="scope.row.refund_amount > 0">
                      <span class="label">退款金额：</span>
                      <span class="value refund">¥{{ scope.row.refund_amount }}</span>
                    </div>
                    <div class="detail-item" v-if="scope.row.refund_status !== -1">
                      <span class="label">退款状态：</span>
                      <span class="value" :class="getRefundStatusClass(scope.row.refund_status)">
                        {{ getRefundStatusText(scope.row.refund_status) }}
                      </span>
                    </div> -->
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="payment_time" label="支付时间" width="160" />
            <el-table-column prop="status" label="订单状态" width="120" fixed="left">
              <template slot-scope="scope">
                <!-- 优先显示退款状态 -->
                <el-tag v-if="scope.row.refund_status !== -1" :type="getRefundStatusType(scope.row.refund_status)">
                  {{ getRefundStatusText(scope.row.refund_status) }}
                </el-tag>
                <!-- 显示订单状态 -->
                <el-tag v-else :type="getOrderStatusType(scope.row.status)">
                  {{ getOrderStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="hotel_level_name" label="酒店" width="120">
              <template slot-scope="scope">
                <div v-if="scope.row.hotel_level_name && scope.row.hotel_level_amount">
                  <div>{{ scope.row.hotel_level_name }}</div>
                  <div style="color: #999; font-size: 12px;">¥{{ scope.row.hotel_level_amount }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="refund_amount" label="退款信息" min-width="200">
              <template slot-scope="scope">
                <div v-if="scope.row.refund_reason">
                  <div>退款金额：{{ scope.row.refund_amount }}</div>
                  <div>退款理由：{{ scope.row.refund_reason }}</div>
                  <div>退款备注：{{ scope.row.refund_remark }}</div>
                  <div>退款结果：{{ scope.row.refund_result }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" width="160">
            </el-table-column>
            <el-table-column prop="order_no" label="订单号" width="200" />
            <el-table-column label="操作" fixed="right" width="150">
              <template slot-scope="scope">
                <!-- <el-button type="text" @click="onEdit(scope.row)">编辑</el-button> -->
                <el-button type="text" @click="onDetail(scope.row)">详情</el-button>
                <el-button v-if="scope.row.status === 'paid' && scope.row.refund_status === -1" type="text" @click="onShip(scope.row)">确认订单</el-button>
                <el-button v-if="scope.row.status !== 'pending' && (scope.row.refund_status === -1 || scope.row.refund_status === 0)" type="text"
                  style="color: #67C23A" @click="onComplete(scope.row)">完成订单</el-button>
                <el-button
                  v-if="scope.row.payment_status === 1 && (scope.row.refund_status === -1 || scope.row.refund_status === 0)"
                  type="text" style="color: #E6A23C" @click="onRefund(scope.row)">
                  {{ scope.row.refund_status === 0 ? '重新申请退款' : '申请退款' }}
                </el-button>
                <el-button v-if="scope.row.refund_status === 1" type="text" style="color: #409EFF"
                  @click="onRefundConfirm(scope.row)">
                  退款处理
                </el-button>
                <el-button type="text" style="color: #F82222" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <div class="page-box">
        <el-pagination background :current-page="pageNo" :page-sizes="pageSizes" :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="totalSize" @size-change="changePageSize"
          @current-change="changePageNo" />
      </div>
    </div>
    <Add ref="addFormRef" @get-page="initData" />
    <Detail ref="detailFormRef" />
    <Ship ref="shipFormRef" @get-page="initData" />

    <!-- 退款确认对话框 -->
    <el-dialog title="申请退款" :visible.sync="refundDialogVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="refundForm" :rules="refundRules" ref="refundFormRef" label-width="100px">
        <el-form-item label="订单号">
          <span>{{ currentRefundOrder.order_no }}</span>
        </el-form-item>
        <el-form-item label="出发日期">
          <span style="color: #67C23A; font-weight: bold;">{{ currentRefundOrder.travel_date }}</span>
        </el-form-item>
        <el-form-item label="用户信息">
          <span>{{ currentRefundOrder.user ? currentRefundOrder.user.nickname : '未知用户' }}</span>
        </el-form-item>
        <el-form-item label="申请退款原因" prop="refund_reason">
          <el-input v-model="refundForm.refund_reason" type="textarea" :rows="3" placeholder="请输入申请退款原因，如：用户申请退款"
            maxlength="255" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund" :loading="refundLoading">确认申请退款</el-button>
      </div>
    </el-dialog>

    <!-- 退款处理对话框 -->
    <el-dialog title="退款处理 - 按损失比例计算" :visible.sync="refundConfirmDialogVisible" width="800px"
      :close-on-click-modal="false">
      <el-form :model="refundConfirmForm" :rules="refundConfirmRules" ref="refundConfirmFormRef" label-width="100px">

        <el-form-item label="订单号">
          <span>{{ currentRefundOrder.order_no }}</span>
        </el-form-item>
        <el-form-item label="支付金额">
          <span style="color: #67C23A; font-weight: bold;">¥{{ currentRefundOrder.payment_amount }}</span>
        </el-form-item>
        <el-form-item label="用户信息">
          <span>{{ currentRefundOrder.user ? currentRefundOrder.user.nickname : '未知用户' }}</span>
        </el-form-item>
        <el-form-item label="退款规则" prop="refund_rule">
          <div class="refund-rule-info">
            <div class="rule-item">
              <span class="rule-label">申请时间：</span>
              <span class="rule-value">{{ formatDateTime(currentRefundOrder.refund_time) }}</span>
            </div>
            <div class="rule-item">
              <span class="rule-label">出行日期：</span>
              <span class="rule-value">{{ formatDate(currentRefundOrder.travel_date) }}</span>
            </div>
            <div class="rule-item">
              <span class="rule-label">损失比例：</span>
              <span class="rule-value" :class="getRefundRuleClass()">{{ getRefundRuleText() }}</span>
            </div>
            <div class="rule-item">
              <span class="rule-label">建议退款：</span>
              <span class="rule-value highlight">¥{{ getSuggestedRefundAmount() }}</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="退款金额" prop="refund_amount">
          <div class="refund-amount-input">
            <el-radio-group v-model="refundConfirmForm.refund_type" @change="onRefundTypeChange">
              <el-radio label="suggested">按损失比例退款 (¥{{ getSuggestedRefundAmount() }})</el-radio>
              <el-radio label="custom">自定义金额</el-radio>
            </el-radio-group>
            <el-input v-if="refundConfirmForm.refund_type === 'custom'" v-model="refundConfirmForm.refund_amount"
              type="number" placeholder="请输入退款金额" :max="currentRefundOrder.payment_amount || 0" step="0.01"
              style="margin-top: 10px;">
              <template slot="prepend">¥</template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="处理结果" prop="approve">
          <el-radio-group v-model="refundConfirmForm.approve">
            <el-radio :label="true">同意退款</el-radio>
            <el-radio :label="false">拒绝退款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理备注" prop="refund_remark">
          <el-input v-model="refundConfirmForm.refund_remark" type="textarea" :rows="3"
            :placeholder="refundConfirmForm.approve ? '请输入退款备注' : '请输入拒绝原因'" maxlength="255" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundConfirmDialogVisible = false">取消</el-button>
        <el-button :type="refundConfirmForm.approve ? 'success' : 'danger'" @click="confirmRefundProcess"
          :loading="refundConfirmLoading">
          {{ refundConfirmForm.approve ? '确认退款' : '确认拒绝' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import crud from "@/mixins/crud";
import { http } from "@/api";
import Add from "./add";
import Detail from "./detail";
import Ship from "./ship";

export default {
  name: "TravelOrderIndex",
  components: {
    Add,
    Detail,
    Ship
  },
  mixins: [crud],
  props: {
    is_group: {
      type: Number,
      default: 0
    },
    travel_sku_stock_id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      request: http.travelOrder,
      searchList: [
        {
          label: '订单号',
          prop: 'order_no',
          name: 'input',
          placeholder: '请输入订单号'
        },
        {
          label: '旅游产品',
          prop: 'travel_name',
          name: 'input',
          placeholder: '请输入旅游产品名称'
        },
        {
          label: '联系人',
          prop: 'contact_name',
          name: 'input',
          placeholder: '请输入联系人姓名'
        },
        {
          label: '联系电话',
          prop: 'contact_phone',
          name: 'input',
          placeholder: '请输入联系电话'
        },
        // {
        //   label: '旅游日期',
        //   prop: 'travel_date',
        //   type: 'daterange',
        //   name: 'date',
        //   placeholder: '请选择旅游日期'
        // }
      ],
      searchParams: {
        order_no: '',
        travel_name: '',
        user_id: '',
        contact_name: '',
        contact_phone: '',
        travel_date: '',
        status: '', // 默认显示全部订单
        refund_status: '' // 退款状态参数
      },
      defaultParams: {
        is_group: 0,
        travel_sku_stock_id: undefined
      },
      tableData: [],
      // 退款相关
      refundDialogVisible: false,
      refundConfirmDialogVisible: false,
      currentRefundOrder: {},
      refundForm: {
        refund_reason: ''
      },
      refundConfirmForm: {
        refund_amount: 0,
        refund_type: 'suggested', // 'suggested': 按规则退款, 'custom': 自定义金额
        approve: true, // true: 同意退款, false: 拒绝退款
        refund_remark: ''
      },
      refundRules: {
        refund_reason: [
          { required: true, message: '请输入退款原因', trigger: 'blur' }
        ]
      },
      refundConfirmRules: {
        refund_amount: [
          {
            validator: (rule, value, callback) => {
              if (this.refundConfirmForm.refund_type === 'custom') {
                if (!value) {
                  callback(new Error('请输入退款金额'));
                } else if (value > this.currentRefundOrder.payment_amount) {
                  callback(new Error('退款金额不能超过支付金额'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        approve: [
          { required: true, message: '请选择处理结果', trigger: 'change' }
        ],
        refund_remark: [
          { required: true, message: '请输入处理备注', trigger: 'blur' }
        ]
      },
      refundLoading: false,
      refundConfirmLoading: false,
      activeTab: 'all' // 新增：控制当前激活的标签页
    }
  },
  watch: {
    travel_sku_stock_id: {
      handler(newVal) {
        this.defaultParams.travel_sku_stock_id = newVal || undefined;
      },
      immediate: true
    },
  },
  created() {
    if (this.is_group) {  
      this.defaultParams.is_group = this.is_group;
    }
  },
  methods: {
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      return new Date(dateTime).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    onDetail(row) {
      this.$refs.detailFormRef.open(row);
    },
    onShip(row) {
      this.$refs.shipFormRef.open(row);
    },
    // 申请退款
    onRefund(row) {
      this.currentRefundOrder = row;
      this.refundForm.refund_reason = row.refund_reason || '';
      this.refundDialogVisible = true;
    },

    // 确认退款申请
    confirmRefund() {
      this.$refs.refundFormRef.validate(async (valid) => {
        if (valid) {
          this.refundLoading = true;
          try {
            await http.travelOrder.refund({
              id: this.currentRefundOrder.id,
              refund_reason: this.refundForm.refund_reason
            });
            this.$message.success('退款申请提交成功');
            this.refundDialogVisible = false;
            this.initData();
          } catch (error) {
            this.$message.error(error.message || '退款申请失败');
          } finally {
            this.refundLoading = false;
          }
        }
      });
    },

    // 退款处理确认
    onRefundConfirm(row) {
      this.currentRefundOrder = row;
      this.refundConfirmForm.refund_type = 'suggested'; // 默认按规则退款
      this.refundConfirmForm.refund_amount = this.getSuggestedRefundAmount(); // 默认设置为建议退款金额
      this.refundConfirmForm.approve = true; // 默认同意
      this.refundConfirmForm.refund_remark = '';
      this.refundConfirmDialogVisible = true;
    },

    // 确认退款处理
    async confirmRefundProcess() {
      this.$refs.refundConfirmFormRef.validate(async (valid) => {
        if (valid) {
          this.refundConfirmLoading = true;
          try {
            await http.travelOrder.refundConfirm({
              id: this.currentRefundOrder.id,
              refund_amount: this.refundConfirmForm.refund_amount,
              approve: this.refundConfirmForm.approve,
              refund_remark: this.refundConfirmForm.refund_remark
            });
            this.$message.success(this.refundConfirmForm.approve ? '退款处理成功' : '退款拒绝成功');
            this.refundConfirmDialogVisible = false;
            this.initData();
          } finally {
            this.refundConfirmLoading = false;
          }
        }
      });
    },

    // 确认订单完成
    async onComplete(row) {
      try {
        await this.$confirm('确认将此订单标记为已完成吗？', '确认完成', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        await http.travelOrder.complete({ id: row.id });
        this.$message.success('订单已完成');
        this.initData();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '操作失败，请重试');
        }
      }
    },

    // 格式化日期显示
    formatDate(dateString) {
      if (!dateString) return '未设置';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
    },

    // 计算退款规则
    calculateRefundRule() {
      if (!this.currentRefundOrder.travel_date) {
        return { ratio: 0, text: '未设置出行日期' };
      }

      const travelDate = new Date(this.currentRefundOrder.travel_date);
      const now = new Date();
      const diffTime = travelDate.getTime() - now.getTime();
      const diffDays = diffTime / (1000 * 60 * 60 * 24);

      // 行程开始前4天18:00(不含)之前 - 无损
      if (diffDays > 4.75) {
        return { ratio: 0, text: '行程开始前4天18:00(不含)之前-无损 (0%)' };
      }
      // 行程开始前4天18:00(含)-行程开始前3天18:00(不含) - 损失20%
      else if (diffDays > 3.75) {
        return { ratio: 0.2, text: '行程开始前4天18:00(含)-行程开始前3天18:00(不含)-损失 (20%)' };
      }
      // 行程开始前3天18:00(含)-行程开始前1天12:00(不含) - 损失40%
      else if (diffDays > 1.5) {
        return { ratio: 0.4, text: '行程开始前3天18:00(含)-行程开始前1天12:00(不含)-损失 (40%)' };
      }
      // 行程开始前1天12:00(含)-行程开始当天00:00(不含) - 损失60%
      else if (diffDays > 0) {
        return { ratio: 0.6, text: '行程开始前1天12:00(含)-行程开始当天00:00(不含)-损失 (60%)' };
      }
      // 行程开始当天 - 损失80%
      else {
        return { ratio: 0.8, text: '行程开始当天-损失 (80%)' };
      }
    },

    // 获取退款规则文本
    getRefundRuleText() {
      return this.calculateRefundRule().text;
    },

    // 获取退款规则样式类
    getRefundRuleClass() {
      const rule = this.calculateRefundRule();
      if (rule.ratio === 0) {
        return 'rule-success'; // 无损 - 绿色
      } else if (rule.ratio <= 0.2) {
        return 'rule-warning'; // 损失20% - 橙色
      } else if (rule.ratio <= 0.4) {
        return 'rule-warning'; // 损失40% - 橙色
      } else if (rule.ratio <= 0.6) {
        return 'rule-warning'; // 损失60% - 橙色
      } else {
        return 'rule-danger'; // 损失80% - 红色
      }
    },

    // 获取建议退款金额
    getSuggestedRefundAmount() {
      const rule = this.calculateRefundRule();
      const paymentAmount = parseFloat(this.currentRefundOrder.payment_amount) || 0;
      // ratio表示损失比例，退款金额 = 支付金额 - 损失金额
      const refundAmount = paymentAmount * (1 - rule.ratio);
      return refundAmount.toFixed(2);
    },

    // 退款类型变化处理
    onRefundTypeChange(type) {
      if (type === 'suggested') {
        this.refundConfirmForm.refund_amount = this.getSuggestedRefundAmount();
      }
    },

    getRefundStatusText(status) {
      const statusMap = {
        '-1': '未退款',
        '0': '退款失败',
        '1': '待处理',
        '2': '退款中',
        '3': '退款成功'
      };
      return statusMap[status] || '未知';
    },
    getRefundStatusClass(status) {
      const classMap = {
        '-1': 'status-normal',
        '0': 'status-warning',
        '1': 'status-success',
        '2': 'status-danger'
      };
      return classMap[status] || '';
    },
    getOrderStatusText(status) {
      const statusMap = {
        'pending': '待付款',
        'paid': '待确认',
        'shipped': '已确认',
        'completed': '已完成',
        'cancelled': '已取消'
      };
      return statusMap[status] || '未知';
    },
    getOrderStatusType(status) {
      const typeMap = {
        'pending': 'warning',
        'paid': 'primary',
        'shipped': 'success',
        'completed': 'success',
        'cancelled': 'info'
      };
      return typeMap[status] || '';
    },
    getRefundStatusType(status) {
      const typeMap = {
        '-1': 'info', // 未退款
        '0': 'danger', // 退款失败
        '1': 'warning', // 待处理
        '2': 'warning', // 退款中
        '3': 'success' // 退款成功
      };
      return typeMap[status] || '';
    },
    calculateTotalPrice(row) {
      let total = 0;

      // 从travelOrderItems获取成人费用
      const adultItems = this.getAdultItems(row);
      if (adultItems.length > 0) {
        total += this.getAdultTotal(row, 'adult');
      }

      // 从travelOrderItems获取儿童费用
      const childItems = this.getChildItems(row);
      if (childItems.length > 0) {
        total += this.getChildTotal(row, 'child');
      }

      // 单房差费用
      total += (row.single_price_diff || 0) * (row.room_count || 0);

      // 酒店费用
      total += (row.hotel_level_amount || 0);

      // 佣金费用
      total += (row.travel_share_price || 0);
      total += (row.travel_share_price2 || 0);

      // 减去退款金额
      total -= (row.refund_amount || 0);

      return total.toFixed(2);
    },

    // 获取成人项目列表
    getAdultItems(row) {
      if (!row.travelOrderItems || !Array.isArray(row.travelOrderItems)) {
        return [];
      }
      return row.travelOrderItems.filter(item =>
        item.traveler_type === 'adult' ||
        item.traveler_type === '成人' ||
        (item.traveler_type && item.traveler_type.toLowerCase().includes('adult'))
      );
    },

    // 获取儿童项目列表
    getChildItems(row) {
      if (!row.travelOrderItems || !Array.isArray(row.travelOrderItems)) {
        return [];
      }
      return row.travelOrderItems.filter(item =>
        item.traveler_type === 'child' ||
        item.traveler_type === '儿童' ||
        (item.traveler_type && item.traveler_type.toLowerCase().includes('child'))
      );
    },

    // 计算成人总价
    getAdultTotal(row, type) {
      const items = this.getAdultItems(row);
      if (items.length === 0) return 0;

      // 如果所有成人项目价格相同，使用第一个价格
      const price = items[0].price || 0;
      return (price * items.length).toFixed(2);
    },

    // 计算儿童总价
    getChildTotal(row, type) {
      const items = this.getChildItems(row);
      if (items.length === 0) return 0;

      // 如果所有儿童项目价格相同，使用第一个价格
      const price = items[0].price || 0;
      return (price * items.length).toFixed(2);
    },

    // 标签页点击事件
    handleTabClick(tab) {
      this.activeTab = tab.name;
      // 根据激活的标签页更新搜索参数
      if (tab.name === 'all') {
        this.searchParams.status = '';
        this.searchParams.refund_status = '';
      } else if (tab.name === 'refund') {
        // 退款/售后标签，设置refund_status=9
        this.searchParams.status = '';
        this.searchParams.refund_status = '9';
      } else {
        this.searchParams.status = tab.name;
        this.searchParams.refund_status = '';
      }
      this.initData();
    },

    // 搜索或重置
    onSearch() {
      // 确保搜索时也使用当前激活的标签页状态
      if (this.activeTab === 'all') {
        this.searchParams.status = '';
        this.searchParams.refund_status = '';
      } else if (this.activeTab === 'refund') {
        this.searchParams.status = '';
        this.searchParams.refund_status = '9';
      } else {
        this.searchParams.status = this.activeTab;
        this.searchParams.refund_status = '';
      }
      this.initData();
    },

    onReset() {
      // 重置搜索条件，但保持当前标签页状态
      this.searchParams.order_no = '';
      this.searchParams.travel_name = '';
      this.searchParams.user_id = '';
      this.searchParams.contact_name = '';
      this.searchParams.contact_phone = '';
      this.searchParams.travel_date = '';
      // 保持当前标签页状态
      if (this.activeTab === 'all') {
        this.searchParams.status = '';
        this.searchParams.refund_status = '';
      } else if (this.activeTab === 'refund') {
        this.searchParams.status = '';
        this.searchParams.refund_status = '9';
      } else {
        this.searchParams.status = this.activeTab;
        this.searchParams.refund_status = '';
      }
      this.initData();
    }
  }
}
</script>

<style scoped lang="scss">
.table-layout {
  margin-top: 20px;
}

.table-handle {
  margin-bottom: 20px;
}

.page-box {
  margin-top: 20px;
  text-align: right;
}

.travel-info {
  display: flex;
  align-items: center;
}

.payment-amount {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.payment-amount:hover {
  color: #409EFF;
}

/* 支付明细弹窗样式 */
.payment-detail-popover {
  .payment-detail {
    .detail-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 6px;
      font-size: 13px;

      .label {
        color: #606266;
        min-width: 80px;
      }

      .value {
        color: #303133;
        font-weight: 500;

        &.highlight {
          color: #E6A23C;
          font-weight: 600;
        }

        &.refund {
          color: #F56C6C;
        }

        &.status-normal {
          color: #909399;
        }

        &.status-warning {
          color: #E6A23C;
        }

        &.status-success {
          color: #67C23A;
        }

        &.status-danger {
          color: #F56C6C;
        }
      }
    }

    hr {
      margin: 8px 0;
      border: none;
      border-top: 1px solid #EBEEF5;
    }
  }
}

.dialog-footer {
  text-align: right;
}

/* 退款规则样式 */
.refund-rule-info {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;

  .rule-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 14px;

    &:last-child {
      margin-bottom: 0;
    }

    .rule-label {
      color: #606266;
      font-weight: 500;
    }

    .rule-value {
      color: #303133;
      font-weight: 500;

      &.highlight {
        color: #E6A23C;
        font-weight: 600;
      }

      &.rule-success {
        color: #67C23A;
      }

      &.rule-warning {
        color: #E6A23C;
      }

      &.rule-danger {
        color: #F56C6C;
      }
    }
  }
}

.refund-amount-input {
  .el-radio-group {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .el-radio {
    margin-right: 0;
    margin-bottom: 5px;
  }
}

/* 订单状态标签页样式 */
.order-status-tabs {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 0 20px;

  .el-tabs__header {
    margin-bottom: 0;
  }

  .el-tabs__content {
    padding: 0;
  }

  .el-tabs__item {
    font-size: 14px;
    padding: 0 20px;

    &.is-active {
      color: #409EFF;
      font-weight: 500;
    }
  }

  .el-tabs__active-bar {
    background-color: #409EFF;
  }
}
</style>